chilebro / [Embed] for clyp.it - 4chan

// ==UserScript==
// @name		[Embed] for clyp.it - 4chan
// @author		chilebro
// @match		https://boards.4chan.org/*/thread/*
// @match		https://boards.4chan.org/*/
// @match		http://boards.4chan.org/*/thread/*
// @match		http://boards.4chan.org/*/
// @icon		https://s.4cdn.org/image/favicon-ws.ico
// @grant		none
// @run-at document-end
// ==/UserScript==
window.magic = function(id) {
    var e = document.getElementById("d-" + id);
    var _e = document.getElementById("e-" + id);
    e.innerHTML.length === 0 ? (e.innerHTML = '<iframe width="100%" height="160" src="https://clyp.it/' + id + '/widget" frameborder="0"></iframe>', _e.innerHTML = "Remove") : (e.innerHTML = "", _e.innerHTML = "Embed");
};

function replacere(match, p1) {
    var id = p1.replace("<wbr>", "");
    return match + (window.Config.linkify ? '</a>' : '') + ' [<a id="e-' + id + '" href="javascript:magic(\'' + id + '\');">Embed</a>]<div class="media-embed" id="d-' + id + '"></div>';
}

function updatemagic() {
    for (var e of document.getElementsByClassName("postMessage")) {
        if (e.getAttribute("displayed") == "1")
            continue;
        e.innerHTML = e.innerHTML.replace(/clyp\.it\/([a-z0-9]*(?:<wbr>)?[a-z0-9]*(?:<wbr>)?[a-z0-9]*(?:<wbr>)?)/gi, replacere);
        e.setAttribute("displayed", "1");
    }
}

document.addEventListener('4chanThreadUpdated', function(e) {
    updatemagic();
}, false);

document.addEventListener('ThreadUpdate', function(e) {
    updatemagic();
}, false);

updatemagic();